package com.bsj.power.sdk.service.handle;

import com.alibaba.fastjson.JSON;
import com.bsj.consumerQ.function.HandleRun;
import com.bsj.consumerQ.method.QueueAndRun;
import com.bsj.power.common.config.cached.RedisCached;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.def.entity.sys.SystemConfig;
import com.bsj.power.common.def.mq.sdk.SdkAnnex;
import com.bsj.power.common.def.mq.sdk.SdkDevice;
import com.bsj.power.common.def.mq.sdk.SdkLoginDevInfo;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.sdk.cache.VideoChCache;
import com.bsj.power.sdk.config.hksdk.HKSDKClientManage;
import com.bsj.power.sdk.config.hksdk.constant.HKSdkConstant;
import com.bsj.power.sdk.config.hksdk.video.VideoOperate;
import com.bsj.power.sdk.service.BasisStart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 海康报警附件处理
 * @date 2024/8/23
 */
@Slf4j
@Component
public class HKSdkHandle implements BasisStart {

    @Value("${annexFile.path}")
    private String path;

    private QueueAndRun fileDownQueue;

    @Autowired
    private RedisCached redisCached;

    @Override
    public void init() {
        //启动消费队列
        fileDownQueue = new QueueAndRun(5, 20, 20);
        fileDownQueue.start("HKSdkFileDown", new HandleRun() {
            @Override
            public void doRun(List<byte[]> list) {
                try {
                    String conf = redisCached.get(RedisConstant.SYS_CONF_MODE);
                    //回溯时长(秒)
                    Integer alarmRunTime = null;
                    if (conf != null) {
                        SystemConfig systemConfig = JSON.parseObject(conf, SystemConfig.class);
                        alarmRunTime = systemConfig.getAlarmRunTime();
                    }
                    if (alarmRunTime == null) {
                        alarmRunTime = 30;
                    }
                    //回朔时长（毫秒）
                    Integer finalAlarmRunTime = alarmRunTime * 1000;
                    list.stream().forEach(item -> {
                        String data = new String(item);
                        SdkAnnex sdkAnnex = JSON.parseObject(data, SdkAnnex.class);
                        SdkDevice deviceInfo = VideoChCache.getDeviceInfo(sdkAnnex.getDevId());
                        if (deviceInfo == null) {
                            log.warn("该设备未加入系统设备ID: {}", sdkAnnex.getDevId());
                            return;
                        }
                        Integer channel = deviceInfo.getCh();
                        if (channel == null) {
                            log.info("设备通道号未知: {}", data);
                            return;
                        }
                        Integer ch = HKSdkConstant.cvr + channel;
                        String vPath = path + sdkAnnex.getPath();
                        //结束时间不变，开始时间为全局规则中配置的时长
                        Date endDate = DateUtils.strToDate(sdkAnnex.getEndTime());
//                        long first = endDate.getTime() - (finalAlarmRunTime * 1000);
//                        String firstHalfMinute = DateUtils.dateToStr(new Date(first));
                        //视频附件开始时间
                        String startTime = DateUtils.dateToStr(new Date(endDate.getTime() - finalAlarmRunTime));
                        //视频附件结束时间
                        String endTime = DateUtils.dateToStr(new Date(endDate.getTime() + finalAlarmRunTime));
                        SdkLoginDevInfo cvrDevInfo = HKSDKClientManage.crvSdkDev.get(deviceInfo.getCvrName());
                        VideoOperate.downloadRecordByTime(cvrDevInfo.getUserId(), ch,
                                startTime, endTime, vPath);
                    });
                } catch (Exception e) {
                    log.error("HKSdkHandle 运行异常: {}", ExceptionUtil.getStackStr(e));
                    return;
                }
            }
        });
    }

    @Override
    public void stop() {
        if (fileDownQueue != null) {
            fileDownQueue.stop();
        }
    }

    @Override
    public void doPush(byte[] bytes) {
        if (fileDownQueue == null) {
            log.error("HKSdkHandle 未初始化");
            init();
        }
        fileDownQueue.push(bytes);
    }

    @Override
    public void doPushObj(Object obj) throws Exception{

    }
}
